package com.dg11185.nearshop.activity.user;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.MyApplication;
import com.dg11185.nearshop.net.request.LoginRequest;
import com.dg11185.nearshop.net.response.LoginResponse;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.ViewUtils;

public class LoginActivity extends SubPageActivity {
    private final static int RESET_PASSWD = 100;
    private final static int REGISTER = 101;
    private final static int MSG_LOGIN_RETURN = 1;

    private EditText acctBox, passwdBox;
    private CheckBox autoLogin, remPasswd;
    private TextView forgetPassw, go_reg;
    private Button login;
    private OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.txt_v_forget_passwd:
                    startActivityForResult(new Intent(mActivity,
                            ResetPassWdActivity.class), RESET_PASSWD);
                    break;

                case R.id.txt_v_go_reg:
                    startActivityForResult(new Intent(mActivity,
                            RegisterActivity.class), REGISTER);
                    break;

                case R.id.btn_login:
                    String acct = acctBox.getText().toString().trim();
                    String passWd = passwdBox.getText().toString().trim();
                    onLogin(acct, passWd);
                    break;
            }

        }

    };
    private OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (buttonView == remPasswd && !isChecked) {
                autoLogin.setChecked(false);
                return;
            }
            if (buttonView == autoLogin && isChecked) {
                remPasswd.setChecked(true);
                return;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setWindowAnimations(R.style.BottomDialog);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setSubPageTitle("会员登录");
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RESET_PASSWD:
                if (resultCode == Activity.RESULT_OK) {
                    acctBox.setText(data.getStringExtra("phoneNum"));
                }
                break;

            case REGISTER:
                if (resultCode == Activity.RESULT_OK) {
                    acctBox.setText(data.getStringExtra("phoneNum"));
                }
                break;
        }

    }

    private void initView() {
        findViewsId();
        forgetPassw.setOnClickListener(clickListener);
        go_reg.setOnClickListener(clickListener);
        login.setOnClickListener(clickListener);
        autoLogin.setOnCheckedChangeListener(checkListener);
        remPasswd.setOnCheckedChangeListener(checkListener);

        // 检测是否有自动登录或者记住密码
        if (mPreferences.getBoolean(Constants.ISAUTOLOGIN, false)) {
            autoLogin.setChecked(true);
            remPasswd.setChecked(true);
            acctBox.setText(mPreferences.getString(Constants.ACCTOUNT, ""));
            passwdBox.setText(mPreferences.getString(Constants.PASSWORD, ""));
        } else if (mPreferences.getBoolean(Constants.REMPASSWD, false)) {
            remPasswd.setChecked(true);
            acctBox.setText(mPreferences.getString(Constants.ACCTOUNT, ""));
            passwdBox.setText(mPreferences.getString(Constants.PASSWORD, ""));
        }

    }

    private void findViewsId() {
        acctBox = (EditText) findViewById(R.id.edit_acct);
        passwdBox = (EditText) findViewById(R.id.edit_passwd);
        autoLogin = (CheckBox) findViewById(R.id.check_auto_login);
        remPasswd = (CheckBox) findViewById(R.id.check_rem_passwd);
        forgetPassw = (TextView) findViewById(R.id.txt_v_forget_passwd);
        go_reg = (TextView) findViewById(R.id.txt_v_go_reg);
        login = (Button) findViewById(R.id.btn_login);

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOGIN_RETURN:
                    LoginResponse res = (LoginResponse) msg.obj;
                    onLoginRet(res);
                    Log.i("test", "login\n" + res.responseStr);
                    break;

                default:
                    break;
            }
        }

    };

    public void onCheckAutoLogin() {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(Constants.ISAUTOLOGIN, true);
        editor.commit();
        remPasswd.setChecked(true);
        onCheckRemPasswd();
    }

    public void onUncheckAutoLogin(boolean isUncheckRemPasswd) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.remove(Constants.ISAUTOLOGIN);
        editor.commit();
        if (isUncheckRemPasswd) {
            remPasswd.setChecked(false);
            onUncheckRemPasswd();
        }
    }

    public void onCheckRemPasswd() {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(Constants.REMPASSWD, true);
        editor.putString(Constants.ACCTOUNT, acctBox.getText().toString()
                .trim());
        editor.putString(Constants.PASSWORD, passwdBox.getText().toString()
                .trim());
        editor.commit();
    }

    public void onUncheckRemPasswd() {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.remove(Constants.REMPASSWD);
        editor.remove(Constants.ACCTOUNT);
        editor.remove(Constants.PASSWORD);
        editor.commit();
    }

    /**
     * 发起登录网络连接
     * 
     * @param acct
     *            账户名
     * @param passWd
     *            密码
     */
    private void onLogin(String acct, String passWd) {
        if (!isStrValid("账户名", acct) || !isStrValid("密码", passWd))
            return;
        showLoading();
        LoginRequest request = new LoginRequest(acct, passWd);
        request.setActionListener(new ActionListener<LoginResponse>() {

            @Override
            public void onSuccess(LoginResponse result) {
                Message msg = new Message();
                msg.obj = result;
                msg.what = MSG_LOGIN_RETURN;
                mHandler.sendMessage(msg);
                hideLoading();
            }

            @Override
            public void onFailure(int resultCode) {
                LogUtils.logNetError("登录失败---" + resultCode);
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    ViewUtils.showToast(mActivity,
                            R.string.cant_connect_network);
                } else {
                    ViewUtils.showToast(mActivity, R.string.network_error);
                }
                hideLoading();
            }
        });
        NetClient.httpPost(request);
    }

    /**
     * 处理登录返回数据
     * 
     * @param res
     */
    private void onLoginRet(LoginResponse res) {
        String status = res.status;
        if (status.equals(LoginResponse.SUCCESS)) {
            // 根据用户设定，选择是否要保存账号密码或者自动登录设置
            if (autoLogin.isChecked()) {
                onCheckAutoLogin();
            } else {
                if (remPasswd.isChecked()) {
                    onUncheckAutoLogin(false);
                    onCheckRemPasswd();
                } else {
                    onUncheckAutoLogin(true);
                }
            }
            MyApplication.setUser(res);
            Intent data = new Intent();
            data.putExtra("loginRes", res);
            setResult(RESULT_OK, data);
            LoginActivity.this.finish();
        } else if (status.equals(LoginResponse.MEM_NOTFOUND)) {
            ViewUtils.showToast(LoginActivity.this, "会员不存在");
            acctBox.setText("");
            passwdBox.setText("");
        } else if (status.equals(LoginResponse.MEM_ILLEGALPWD)) {
            ViewUtils.showToast(LoginActivity.this, "密码错误");
            passwdBox.setText("");
        } else {
            LogUtils.logNetError("登录失败---"+status);
            ViewUtils.showToast(LoginActivity.this, R.string.network_error);
        }
    }

    /**
     * 判断字符串是否合法
     * 
     * @param strName
     *            字符串名
     * @param str
     *            字符串内容
     * @return 合法为true，非法为false
     */
    private boolean isStrValid(String strName, String str) {
        if (str == null || str.length() == 0) {
            ViewUtils.showToast(this, strName + "不能为空");
            return false;
        } else if (strName.equals("密码") && str.length() < 6) {
            ViewUtils.showToast(this, "密码不能少于6位");
            return false;
        }
        return true;
    }

}
